package root.action;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Demo
 */
@WebServlet("/Demo")
public class Demo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Demo() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		浏览器服务器通讯时  默认 是没有状态会话的，也就是说服务器端没有session对象
		
		response.setCharacterEncoding("utf-8");
//		httpsession 是会话数据的存储空间，相当于一个hashmap
		HttpSession session =  request.getSession();
		String sessionid = session.getId();
		System.out.println(sessionid);
//		判断是否是新的httpsession对象
		session.isNew();
		
//		jsessionid 保存在哪里
		Cookie[] cookies = request.getCookies();
		if(cookies!=null)
		for (Cookie cookie : cookies) {
			String name = cookie.getName();
			String value = cookie.getValue();
			int maxage = cookie.getMaxAge();
			
			if(name.equalsIgnoreCase("JSESSIONID")){
				cookie.setMaxAge(60*30);
				response.getWriter().write("old");
			}
		}
		
		session.setAttribute("key", "value1");
		session.setAttribute("key", "value2");
		session.setAttribute("key", "value3");
		session.getAttribute("key");
		session.removeAttribute("key");
		
//		session.setMaxInactiveInterval(60*30); session 默认保存30min
//		如果没有再读取这个session 就清除，如果期间内访问一次，
//		这个期限就会被刷新。
		
//		安全推出
//		在服务器端 解除 jsessionid 与 httpsession对象的绑定关系
		session.invalidate();
		
//		创建游离态的cookie数据
		Cookie cookie = new Cookie("JSESSIONID",session.getId());
		cookie.setHttpOnly(true);
//		设置jsessionid 的最大生命时长与session相同，就能做到关闭浏览器后
//		重新访问网址登录状态还在。
		cookie.setMaxAge(60*30);
//		添加cookie 对象
		response.addCookie(cookie);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
